package Q257;

import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树的所有路径
 *
 * @author 23737
 * @time 2021.11.26
 */
public class Test {
    public static void main(String[] args) {

    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 * dfs
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        List<Integer> paths = new ArrayList<>();
        dfs(root,paths,list);
        return list;
    }
    //回溯
    private void dfs(TreeNode root, List<Integer> paths, List<String> list) {
        paths.add(root.val);
        // 叶子结点
        if (root.left == null && root.right == null) {
            // 输出
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paths.size() - 1; i++) {
                sb.append(paths.get(i)).append("->");
            }
            sb.append(paths.get(paths.size() - 1));
            list.add(sb.toString());
            return;
        }
        if (root.left != null) {
            dfs(root.left, paths, list);
            paths.remove(paths.size() - 1);// 回溯
        }
        if (root.right != null) {
            dfs(root.right, paths, list);
            paths.remove(paths.size() - 1);// 回溯
        }
    }
}
